package com.titan.demo.camel.sample.eip.enricher;

import org.apache.camel.CamelContext;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.processor.aggregate.AggregationStrategy;

import com.titan.demo.camel.utils.RunCamel;

public class TestEnrich {
	public static void main(String[] args) {
        try {
        	RouteBuilder route = createRouteBuilder();
        	createRunCamel().run(route);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	
	private static RunCamel createRunCamel() {
		return new RunCamel() {
			protected void execute(CamelContext context,
					ProducerTemplate producer, ConsumerTemplate consumer)
					throws Exception {
				producer.sendBody("direct:in", "源数据");
			}
		};
	}
	
	private static RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from("direct:in")
                .to("stream:out")
                .enrich("direct:resource", new AggregationStrategy() {
					public Exchange aggregate(Exchange original, Exchange resource) {
						Object originalBody = original.getIn().getBody();
						Object resourceResponse = resource.getIn().getBody();
						Object mergeResult = "original["+originalBody+"];  resource["+resourceResponse+"]"; 
						if (original.getPattern().isOutCapable()) {
							original.getOut().setBody(mergeResult);
						} else {
							original.getIn().setBody(mergeResult);
						}
						return original;
					}
                })
                .to("stream:out")
                ;

                from("direct:resource")
                .transform().simple("被合并数据")
                .setBody(body().append("。"))
                .to("stream:out")
                ;
            }
        };
    }
}
